<template>
  <div class="fa">
    <HeaderTitle title="样本登记"></HeaderTitle>
    <div style="width=100%;height:40px; position: relative;">
      <!-- <a-button type="primary" @click="huoq" style="position: absolute; right: 0">导入样本信息</a-button> -->
    </div>
    <a-row :gutter="[0, 10]">
      <a-col :span="8">
        <a-form :model="dynamicValidateForm" name="basic" :label-col="{ span: 6 }" :wrapper-col="{ span: 14 }"
          autocomplete="off">
          <a-form-item name="area" label="样本模板">
            <a-select @change="change" v-model:value="dynamicValidateForm.area" :options="areas" />
          </a-form-item>
        </a-form>
      </a-col>
    </a-row>
    <CustomerForm @delhandle="delhandle" :count="tableData.length" @resetting="resetting2" :showbon="false"
      @register="register" @handle="handle" ref="RefChilde"></CustomerForm>
    <HeaderTitle :title="title"></HeaderTitle>
    <div class="card_wrap">
      <div class="c_item" v-for="item in tableData" :key="item.id">
        <a-input @change="inpChange()" v-model:value="item.serial"></a-input>
      </div>
    </div>
    <a-drawer v-model:visible="visible" class="custom-class" style="" width="70%" placement="right" @close="onclose">
      <HeaderTitle title="打印标签"></HeaderTitle>
      <div>
        <vxe-table ref="xTable1" border="none" max-height="800" :data="tableData">
          <vxe-column type="checkbox" width="60"></vxe-column>
          <vxe-column field="serial" title="数字编号"></vxe-column>
          <vxe-column field="projectName" title="项目组"></vxe-column>
          <vxe-column field="originalSerial" title="样本编号"></vxe-column>
          <vxe-column field="name" title="样本名称"></vxe-column>
          <vxe-column field="specimen_type" title="样本类型"></vxe-column>
          <vxe-column field="sampleTime" title="采样日期"></vxe-column>
          <vxe-column field="capacity" title="容量" :formatter="({ row }) => row.capacity + row.countUnit"></vxe-column>
        </vxe-table>
      </div>
      <div style="width: 100%; margin-top: 20px; text-align: center">
        <a-button @click="cancel">取消</a-button>
        <a-button type="primary" style="margin: 0 15px" @click="state.showPrintModal = true">打印</a-button>
      </div>
    </a-drawer>
    <leadinginport :showModal="showModal" @echo="echo"></leadinginport>
    <div style="text-align: center; margin-top: 42px">
      <a-button type="primary" @click="resetting" :loading="false">重置</a-button>
      <a-button type="primary" @click="submit" style="margin-left: 10px">保存</a-button>
    </div>

    <Modal v-model:visible="state.showPrintModal" title="打印标签">
      确认打印标签吗
      <template #footer>
        <Button @click="state.showPrintModal = false">取消</Button>
        <Button type="primary" @click="printFn">打印</Button>
      </template>
    </Modal>
  </div>
</template>
<script setup lang="tsx">
import HeaderTitle from '@/components/headerTitle.vue';
import CustomerForm from '@/components/customerForm.vue';
import leadinginport from '../../components/leadinginport.vue';
import { getSampleTemplate } from '../../api/template-management';
import { ref, reactive, nextTick } from 'vue';
import { postregister, Patchregister } from '../../api/register';
import { message, Button, Modal } from 'ant-design-vue';
import { getdetailed } from '../../api/takeNotes';
import { useRoute } from 'vue-router';
import dayjs from 'dayjs';
import { printBoxs } from '@/libs/print';
import { unitCheck } from '@/libs/utils';
const dynamicValidateForm = reactive({
  area: 'specimen_fields',
});
const num = reactive({
  max: 0,
  min: 0,
});
const title = ref(`编码信息  (${num.min}/${num.max})`);
const areas = ref();
const route = useRoute();
const tableData: any = ref([]);
const visible: any = ref(false);
const showModal: any = ref(false);
const state = reactive({
  checkedList: [],
  printData: {
    type: '1',
  },
  showExportModal: false,
  showPrintModal: false,
});
const isvxetable: any = ref(false);
const RefChilde = ref();
const SampleTemplate = async () => {
  const { result } = await getSampleTemplate(null);
  result.data.forEach((item) => {
    item.label = item.name;
    item.value = item.id;
  });
  areas.value = result.data;
  areas.value.push({ label: '默认模板', value: 'specimen_fields' });
};
SampleTemplate();
const handle = (value) => {
  tableData.value.push(...value);
  isvxetable.value = true;
  modifyMix()
};
// 取消
const cancel = () => {
  visible.value = false;
  onclose();
};
// 导入样本信息回显
const echo = (val) => {
  RefChilde.value?.Feedback(val);
  showModal.value = false;
  if (val.strainInstanceEntityList) {
    tableData.value = val.strainInstanceEntityList;
    modifyMix()
  }
};
const detailed = async () => {
  const { result } = await getdetailed(route.query.id);
  result.extDataList.forEach((item) => {
    result[item.key] = item.value;
  });
  tableData.value = result;
  echo(tableData.value);
  dynamicValidateForm.area = result.formworkId;
};
if (route.query.id) {
  detailed();
} else {
  nextTick(() => {
    echo({ groupId: 'specimen_fields' });
    dynamicValidateForm.area = 'specimen_fields';
  });
}

const inpChange = () => {
  modifyMix()
};
// 判断数字编号是否重复
const containsDuplicate = (nums) => {
  return nums.length !== [...new Set(nums)].length;
};
// 保存
const submit = async () => {
  if (tableData.value.length == 0) return message.warning('编码信息不能为空');
  if (tableData.value.some((item) => item.serial == '')) return message.warning('编码信息不能为空');
  if (containsDuplicate(tableData.value.map((item) => item.serial))) return message.warning('编码信息有重复');
  RefChilde.value.preserve();
};
// 回调保存登记
const register = async (val) => {
  if (route.query.id) {
    await Patchregister(
      {
        ...val,
        specimenId: route.query.id,
        strainInstanceEntityList: tableData.value,
        id_card: '429006200000000000',
        formworkId: dynamicValidateForm.area ? dynamicValidateForm.area : 'specimen_fields',
      },
      route.query.id,
    );
  } else {
    await postregister({
      ...val,
      strainInstanceEntityList: tableData.value,
      id_card: '429006200000000000',
      formworkId: dynamicValidateForm.area ? dynamicValidateForm.area : 'specimen_fields',
    });
  }

  let arr = [];
  if (val.extDataList) {
    val.extDataList.forEach((item) => {
      if (item.key.split('_')[0] == 'specimen') {
        arr.push(item.value);
      }
    });
  }
  tableData.value.forEach((item) => {
    item.projectName = val.projectName;
    item.bymc = val.bymc;
    item.name = val.name;
    item.categoryName = val.categoryName;
    item.originalSerial = val.originalSerial;
    item.sampleTime = dayjs(val.sampleTime).format('YYYY-MM-DD');
    item.capacity = val.capacity;
    item.specimen_type = arr.join('|');
    item.countUnit = val.countUnit;
  });
  visible.value = true;
  nextTick(() => {
    xTable1.value.loadData(tableData.value);
  });
};
//重置
const resetting = () => {
  tableData.value = [];
  RefChilde.value.resetting();
};
const resetting2 = () => {
  num.max = 0;
  num.min = 0;
  title.value = `编码信息  (${num.min}/${num.max})`;
  dynamicValidateForm.area = 'specimen_fields';
};
const onclose = () => {
  resetting();
  visible.value = false;
};
//导出
const xTable1 = ref();
//切换模板
const change = (value) => {
  RefChilde.value.templateCV(value);
};
// 打印
const printFn = async () => {
  printBoxs(tableData.value);
};
//减少数量
const delhandle = (index) => {
  tableData.value.splice(index);
  modifyMix()
};
//改变数字编码的计数
const modifyMix = () => {
  tableData.value.forEach(item => {
    item.serial = item.serial.replace(/\s+/g, '')
  })
  let arr = tableData.value.filter((item) => item?.serial != '');
  num.max = tableData.value.length;
  num.min = arr.length;
  title.value = `编码信息  (${num.min}/${num.max})`;
}
</script>
<style lang="less" scoped>
.fa {
  width: 100%;
  background-color: #fff;
  padding: 5px;
  padding-bottom: 20px;
}

.card_wrap {
  // 大盒子
  width: 98%;
  display: flex;
  flex-wrap: wrap;
  justify-content: flex-start; // 替代原先的space-between布局方式
}

.c_item {
  // 每个item
  flex: 1;
  height: 30px;
  // border: 1px solid #ccc;
  width: calc((100% - 10px) / 10); // 这里的10px = (分布个数3-1)*间隙5px, 可以根据实际的分布个数和间隙区调整
  min-width: calc((100% - 10px) / 10); // 加入这两个后每个item的宽度就生效了
  max-width: calc((100% - 10px) / 10); // 加入这两个后每个item的宽度就生效了

  &:nth-child(10n) {
    // 去除第3n个的margin-right
    margin-right: 0;
  }
}
</style>
